package com.darrylsite.ihm;

import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.darrylsite.core.MyEntityManager;
import com.darrylsite.entite.Groupe;
import java.awt.Dimension;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JFrame;

/**
 *
 * @author  Nabster
 */
public class GroupeIHM extends javax.swing.JPanel implements KeyListener
{

    private long modifiedId = -1;

    /** Creates new form Groupe */
    public GroupeIHM()
    {
        initComponents();
        processSwingEvent();
        lstGroupes.addKeyListener(this);
    }

    private List<com.darrylsite.entite.Groupe> retrievegroupList()
    {
        EntityManager em = MyEntityManager.emf.createEntityManager();
        Query query = em.createQuery("select g from Groupe g order by g.id");
        return query.getResultList();
    }

    private void loadGroupList()
    {
        List<com.darrylsite.entite.Groupe> liste = retrievegroupList();
        List<String> groupes = new ArrayList<String>();

        for (int i = 0; i < liste.size(); i++)
        {
            groupes.add(liste.get(i).getName());
        }
        lstGroupes.setListData(groupes.toArray());
    }

    private void clearField()
    {
        txtNom.setText("");
        txtDesc.setText("");
        modifiedId = -1;
        btCreate.setText("Creer");
    }

    private void createGroup()
    {
        if (txtNom.getText().equals(""))
        {
            return;
        }
        if (modifiedId != -1)
        {
            updateGroup();
            return;
        }
        com.darrylsite.entite.Groupe grp = new com.darrylsite.entite.Groupe();
        grp.setName(txtNom.getText());
        grp.setComment(txtDesc.getText());

        List<Groupe> groupes = retrievegroupList();
        for (Groupe g : groupes)
        {
            if (g.getName().equalsIgnoreCase(txtNom.getText()))
            {
                return;
            }
        }

        EntityManager em = MyEntityManager.emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(grp);
        em.flush();
        em.getTransaction().commit();
        loadGroupList();
    }

    private void updateGroup()
    {
        EntityManager em = MyEntityManager.emf.createEntityManager();
        com.darrylsite.entite.Groupe grp = new com.darrylsite.entite.Groupe();
        grp.setName(txtNom.getText());
        grp.setComment(txtDesc.getText());
        grp.setId(modifiedId);
        em.getTransaction().begin();
        em.merge(grp);
        em.getTransaction().commit();
        loadGroupList();
    }

    private void editGroup()
    {
        int i = lstGroupes.getSelectedIndex();
        if (i < 0)
        {
            return;
        }
        String chaine = (String) lstGroupes.getSelectedValue();
        //String[] tb = chaine.split(" : ");
        EntityManager em = MyEntityManager.emf.createEntityManager();
        Query query = em.createQuery("select g from Groupe g where g.name='"
                + chaine + "'");
        com.darrylsite.entite.Groupe grp = (com.darrylsite.entite.Groupe) query.getSingleResult();
        modifiedId = grp.getId();
        txtDesc.setText(grp.getComment());
        txtNom.setText(grp.getName());
        btCreate.setText("Modifier");
    }

    private void processSwingEvent()
    {
        EventQueue.invokeLater(new Runnable()
        {

            @Override
            public void run()
            {
                loadGroupList();
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtNom = new javax.swing.JTextField();
        btCreate = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtDesc = new javax.swing.JTextPane();
        jLabel4 = new javax.swing.JLabel();
        btDelete = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        lstGroupes = new javax.swing.JList();

        setLayout(new java.awt.BorderLayout());

        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("Nom du groupe ");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 14, 97, -1));
        jPanel1.add(txtNom, new org.netbeans.lib.awtextra.AbsoluteConstraints(111, 11, 240, -1));

        btCreate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.png"))); // NOI18N
        btCreate.setText("Ajouter");
        btCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCreateActionPerformed(evt);
            }
        });
        jPanel1.add(btCreate, new org.netbeans.lib.awtextra.AbsoluteConstraints(141, 174, 99, -1));

        jScrollPane2.setViewportView(txtDesc);

        jPanel1.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(113, 37, 238, 109));

        jLabel4.setText("Description :");
        jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 62, -1, -1));

        btDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cross.png"))); // NOI18N
        btDelete.setText("Effacer");
        btDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDeleteActionPerformed(evt);
            }
        });
        jPanel1.add(btDelete, new org.netbeans.lib.awtextra.AbsoluteConstraints(246, 174, 105, -1));

        lstGroupes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                onChooseEdit(evt);
            }
        });
        jScrollPane3.setViewportView(lstGroupes);

        jPanel1.add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(369, 16, 190, 260));

        jPanel2.add(jPanel1, java.awt.BorderLayout.CENTER);

        add(jPanel2, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void onChooseEdit(java.awt.event.MouseEvent evt)
    {
        editGroup();
    }

    private void btDeleteActionPerformed(java.awt.event.ActionEvent evt)
    {
        clearField();
    }

    private void btCreateActionPerformed(java.awt.event.ActionEvent evt)
    {
        createGroup();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCreate;
    private javax.swing.JButton btDelete;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JList lstGroupes;
    private javax.swing.JTextPane txtDesc;
    private javax.swing.JTextField txtNom;
    // End of variables declaration//GEN-END:variables

    public static void main(String... args)
    {
        JFrame frame = new JFrame("thest");
        frame.setSize(new Dimension(400, 400));
        frame.setContentPane(new GroupeIHM());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }

    @Override
    public void keyTyped(KeyEvent e)
    {
        if (e.getKeyChar() != KeyEvent.VK_DELETE)
        {
            return;
        }

        Object[] valeurs = lstGroupes.getSelectedValues();
        List<Groupe> groupes = retrievegroupList();
        EntityManager em = MyEntityManager.emf.createEntityManager();
        for (Groupe g : groupes)
        {
            for (Object s : valeurs)
            {
                if (s.toString().equalsIgnoreCase(g.getName()))
                {
                    em.getTransaction().begin();
                    em.remove(em.merge(g));
                    em.getTransaction().commit();
                }
            }
        }
        loadGroupList();
    }

    @Override
    public void keyPressed(KeyEvent e)
    {
    }

    @Override
    public void keyReleased(KeyEvent e)
    {
    }
}
